package com.carbeauty.image.indexing;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.semanticmetadata.lire.DocumentBuilder;
import net.semanticmetadata.lire.imageanalysis.bovw.SurfFeatureHistogramBuilder;
import net.semanticmetadata.lire.utils.LuceneUtils;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;

import com.carbeauty.image.Constants;


public class ImageIndexThread {
    public static ArrayList<String> getAllImages(File directory, boolean descendIntoSubDirectories) throws IOException {
        ArrayList<String> resultList = new ArrayList<String>(256);
        File[] f = directory.listFiles();
        for (File file : f) {
            if (file != null && (file.getName().toLowerCase().endsWith(".jpg") || file.getName().toLowerCase().endsWith(".png")) && !file.getName().startsWith("tn_")) {
                resultList.add(file.getCanonicalPath());
            }
            if (descendIntoSubDirectories && file.isDirectory()) {
                ArrayList<String> tmp = getAllImages(file, true);
                if (tmp != null) {
                    resultList.addAll(tmp);
                }
            }
        }
        if (resultList.size() > 0)
            return resultList;
        else
            return null;
    }
    boolean isCreatIndex = true;
    public void indexMissingAction() {
        try {
            IndexReader reader = IndexReader.open(FSDirectory.open(new File(Constants.INDEX_NAME)), true);
            SurfFeatureHistogramBuilder builder = new SurfFeatureHistogramBuilder(reader, reader.maxDoc()/10, 2000);
            builder.indexMissing();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void createIndex()
    {
    	 java.util.ArrayList<java.lang.String> images;
		try {
			images = getAllImages( new java.io.File(Constants.FILE_UPLOAD_DIR), true);
			 if (images == null) {
	             return;
	         }
			 createIndex(images);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    public void createIndex(java.util.ArrayList<java.lang.String> images ){
        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
        df.setMaximumFractionDigits(10);
        df.setMinimumFractionDigits(0);
        try {
            IndexWriter   iw = LuceneUtils.createIndexWriter(Constants.INDEX_NAME, isCreatIndex);
//            if(isCreatIndex){
//            	iw.deleteAll();
//            }
            isCreatIndex = false;
            DocumentBuilder builder = new MetadataBuilder();
            int count = 0;
            long time = System.currentTimeMillis();
            Document doc;
            ImageIndexer indexer = new ImageIndexer(images, builder);
            new Thread(indexer).start();
            while ((doc = indexer.getNext()) != null) {
                try {
                    iw.addDocument(doc);
                } catch (Exception e) {
                    System.err.println("Could not add document.");
                    e.printStackTrace();
                }
                count++;
                float percentage = (float) count / (float) images.size();
                float msleft = (float) (System.currentTimeMillis() - time) / percentage;
                float secLeft = msleft * (1 - percentage) / 1000f;
                String toPaint = "~ " + df.format(secLeft) + " sec. left";
                if (secLeft > 90) toPaint = "~ " + Math.ceil(secLeft / 60) + " min. left";
                System.out.println(toPaint);
            }
            long timeTaken = (System.currentTimeMillis() - time);
            float sec = ((float) timeTaken) / 1000f;
            System.out.println("Finished indexing ...");
            iw.optimize();
            iw.close();
            
        } catch (IOException ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        }
    }
    
    public void  createImageIndex(String photo) throws IOException{
    	java.util.ArrayList<java.lang.String> images=  new java.util.ArrayList<java.lang.String>();
    	images.add(photo);
    	createIndex(images);
    	System.out.println("添加索引完成："+photo);
    }
    
    public static void main(String[] argts)
    {
    	
    	new ImageIndexThread().createIndex();
    	
    }
}
